﻿using System;
using DotNetNuke.Modules._2DoTasks.Components;
using DotNetNuke.Modules._2DoTasks.Components.Controllers;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;

namespace DotNetNuke.Modules._2DoTasks
{
    public partial class TaskComments : _2DoTasksModuleBase
    {
        #region "Properties"

        /// <summary>
        /// Property for the comment info
        /// </summary>
        public string Comment
        {
            get
            {
                return txt_comment.Text.Trim();
            }
        }

        #endregion "Properties"

        #region "Events"

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                FillLanguages();

                //Implement your edit logic for your module
                if (!Page.IsPostBack)
                {
                    if (TaskId.HasValue)
                    {
                        BindTaskComments(TaskId.Value);
                    }
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        protected void lst_comments_LayoutCreated(object sender, EventArgs e)
        {
        }

        protected void lst_comments_ItemDataBound(object sender, System.Web.UI.WebControls.ListViewItemEventArgs e)
        {
        }

        #endregion "Events"

        #region "Aux Functions"

        /// <summary>
        /// Adds a new comment
        /// </summary>
        public void SaveTaskComment(UnitOfWork uof)
        {
            TaskCommentController taskCommentController =
                new TaskCommentController(uof, TaskId.Value);
            taskCommentController.Add(new Components.Entities._TaskComment
            {
                Comment = txt_comment.Text.Trim()
            });
        }

        /// <summary>
        /// Fills the language data into the respective controls
        /// </summary>
        private void FillLanguages()
        {
            lt_commentHistory.Text = Localization.GetString("lt_commentHistory", this.LocalResourceFile);
        }

        /// <summary>
        /// Gets the task comments and binds them into the respective controls
        /// </summary>
        /// <param name="taskId"> the task to collect comments from</param>
        private void BindTaskComments(int taskId)
        {
            //fill existing task comments
            using (UnitOfWork uof = new UnitOfWork(PortalId, ModuleId))
            {
                TaskCommentController taskCommentController = new TaskCommentController(uof, taskId);
                lst_comments.DataSource = taskCommentController.GetAll();
                lst_comments.DataBind();
            }
        }

        #endregion "Aux Functions"
    }
}